<template>
  <div class="goodList">
    <HeadInfo></HeadInfo>
    <a-card>
      <div>
        <a-space class="operator">
          <a-button type="primary" @click="add">新建</a-button>
        </a-space>
        <standard-table
          :columns="columns"
          :dataSource="data"
          :rowKey="
            (record, index) => {
              return index;
            }
          "
        >
          <div slot="description" slot-scope="{ text }">
            {{ text }}
          </div>
          <template slot="valueName" slot-scope="{ record }">
            <div
              v-for="(item, index) in record.s_attributesValues"
              :key="index"
              class="valueImgWrapper"
            >
              {{ item.attribute_value }}
              <div class="valueImg">
                <img :src="item.photo" alt="" />
              </div>
            </div>
          </template>
          <div slot="operation" slot-scope="{ record }">
            <a @click="edit(record)" style="margin-right: 8px">
              <a-icon type="edit" />编辑
            </a>
            <a @click="del(record)" style="margin-right: 8px">
              <a-icon type="delete" />删除
            </a>
          </div>
          <template slot="statusTitle">
            <a-icon @click.native="onStatusTitleClick" type="info-circle" />
          </template>
        </standard-table>
      </div>
    </a-card>
    <!-- 新建or修改keyValue -->
    <a-drawer
      v-if="skuVisible"
      title="新增或修改规格"
      :width="600"
      :visible.sync="skuVisible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
    >
      <a-form ref="formRef" :model="dynamicValidateForm">
        <h3>规格名</h3>
        <a-form-item>
          <a-input
            style="width: 160px"
            v-model="dynamicValidateForm.keyName"
            size="small"
          ></a-input>
        </a-form-item>
        <a-form-item
          v-for="(domain, index) in dynamicValidateForm.valueName"
          :key="domain.key"
          :label="'规格值'"
          :name="['domains', index, 'value']"
          style="border: 1px solid black"
          class="demo"
        >
          <div>
            <a-input
              v-model="domain.value"
              placeholder="请输入规格值"
              style="width: 160px; margin-right: 8px"
            />
            <span
              v-if="dynamicValidateForm.valueName.length > 1"
              class="dynamic-delete-button"
              :disabled="dynamicValidateForm.valueName.length === 1"
              @click="removeDomain(domain)"
            >
              del
            </span>
            <!-- <MinusCircleOutlined
            v-if="dynamicValidateForm.domains.length > 1"
            class="dynamic-delete-button"
            :disabled="dynamicValidateForm.domains.length === 1"
            @click="removeDomain(domain)"
          /> -->
            <a-upload
              :action="uploadUrl2"
              :headers="headers"
              :show-upload-list="false"
              list-type="picture-card"
              class="upload-list-inline"
              @change="handleChange(index, $event)"
              :data="uploadData"
            >
              <img v-if="domain.photo" :src="domain.photo" alt="avatar" />
              <div v-else>
                <a-icon type="plus" />
                <div class="ant-upload-text">点击上传</div>
              </div>
            </a-upload>
          </div>
        </a-form-item>
        <a-form-item>
          <a-button type="dashed" style="width: 60%" @click="addDomain">
            添加规格值
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" @click="submitForm"
            >确定</a-button
          >
          <a-button style="margin-left: 10px" @click="resetForm">取消</a-button>
        </a-form-item>
      </a-form>
    </a-drawer>
    <a-modal
      v-model="delModal"
      title="温馨提示"
      ok-text="确认"
      cancel-text="取消"
      @ok="deleteRecord"
    >
      是否删除该商品规格
    </a-modal>
  </div>
</template>

<script>
import StandardTable from '@/pages/components/table/StandardTable';
import HeadInfo from '@/pages/components/detail/HeadInfo';
import { mapState } from 'vuex';
import {
  getKeyValue,
  addKeyValue,
  delKeyValue,
  updateKeyValue,
  delValue,
} from '@/services/shopApi/sku';
import { userinfo } from '@/services/user';
import getCookie from '@/utils/getCookie';
import { UPLOADGOODS } from '@/services/shopApi/api';
const columns = [
  {
    title: '规格名称',
    dataIndex: 'keyName',
    key: 'keyName',
  },
  {
    title: '规格值',
    dataIndex: 'valueName',
    key: 'valueName',
    scopedSlots: { customRender: 'valueName' },
  },
  {
    title: '操作',
    key: 'operation',
    scopedSlots: { customRender: 'operation' },
  },
];
export default {
  name: 'classify',
  components: { HeadInfo, StandardTable },
  mounted() {
    this.uploadUrl2 = UPLOADGOODS;
    this.headers['authorization'] = getCookie('Authorization');
  },
  data() {
    return {
      uploadData: { type: 1 },
      headers: {},
      uploadUrl2: [],
      dynamicValidateForm: {
        keyName: '',
        valueName: [],
      },
      projectId: 0,
      tag: '',
      tagChange: '',
      type: 0, //0是新增 1是修改
      typeName: '',
      columns,
      data: [],
      id: '',
      delModal: false,
      skuVisible: false,
      showEditModal: false,
      tags: [],
      inputVisible: false,
      inputValue: '',
      loading: false,
      desc: '添加商品规格,更好的管理你自己的商品',
      chosenObj: {},
      dataSource: [],
    };
  },
  computed: {
    ...mapState('account', ['user']),
  },
  methods: {
    // 图片上传状态改变
    handleChange(i, e) {
      if (e.file.status === 'done') {
        this.dynamicValidateForm.valueName[i].photo =
          e.file.response.result.path;
      }
    },
    async removeDomain(item) {
      let index = this.dynamicValidateForm.valueName.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.valueName.splice(index, 1);
      }
      await delValue(item.id);
    },
    async submitForm() {
      if (this.type == 0) {
        let obj = {
          project_id: this.projectId,
          keyName: this.dynamicValidateForm.keyName,
          valueName: this.dynamicValidateForm.valueName.map((ele) => {
            return {
              value: ele.value,
              photo: ele.photo,
            };
          }),
        };

        await addKeyValue(obj);
        this.getKey();
      } else {
        await updateKeyValue(this.dynamicValidateForm);
        this.getKey();
      }
      this.skuVisible = false;
    },
    resetForm() {
      this.skuVisible = false;
    },
    addDomain() {
      this.dynamicValidateForm.valueName.push({
        value: '',
        key: Date.now(),
        photo: '',
      });
    },
    cancel() {
      this.skuVisible = false;
    },
    onClose() {
      this.skuVisible = false;
    },
    handleClose(removedTag) {
      const tags = this.tags.filter((tag) => tag !== removedTag);
      this.tags = tags;
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.inputRef.focus();
      });
    },
    handleInputConfirm() {
      const inputValue = this.inputValue;
      let tags = this.tags;
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue];
      }
      Object.assign(this, {
        tags,
        inputVisible: false,
        inputValue: '',
      });
    },
    add() {
      this.dynamicValidateForm = {
        keyName: '',
        valueName: [],
      };
      this.type = 0;
      this.skuVisible = true;
    },

    edit(data) {
      this.type = 1;
      this.skuVisible = true;
      this.dynamicValidateForm.keyId = data.id;
      this.dynamicValidateForm.keyName = data.keyName;
      this.dynamicValidateForm.valueName = data.s_attributesValues.map(
        (ele) => {
          return {
            id: ele.id,
            value: ele.attribute_value,
            photo: ele.photo,
          };
        }
      );
    },
    del(data) {
      this.chosenObj = data;
      this.delModal = true;
    },
    async deleteRecord() {
      await delKeyValue(this.chosenObj.id);
      this.delModal = false;
      this.getKey();
    },
    async getKey() {
      let res = await getKeyValue({ project_id: this.projectId });
      this.data = res.result;
    },
  },
  async created() {
    let res = await userinfo();
    this.projectId = res.result.project_id;
    this.getKey();
  },
};
</script>

<style lang="less" scoped>
.demo {
  display: flex;
  justify-content: left;
  align-items: top;
}
.valueImgWrapper {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.valueImg {
  width: 80px;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    display: block;
    width: 100%;
  }
}
</style>
